<?php

namespace app\api\controller\pifa;

use app\common\controller\Api;
use think\Config;
use think\Db;
use think\Validate;
use think\Session;
use fast\WechatMini;
use fast\Feiyong;
use addons\third\model\Third;
use think\Log;
use think\Request;
use fast\Http;
use think\Exception;
use addons\third\library\Service;
use app\api\model\Goodsitem;
use addons\epay\library\Service as PayService;
use app\api\library\Order as PayOrder;
use fast\Tongbu;
use addons\litestore\model\Litestorefreight;
use addons\litestore\model\Wxlitestoregoods;

use fast\AdapayUtil;
use fast\Saobei;


class Kill extends Api
{

    protected $noNeedLogin = ['login','getconfig','getMendian1','token','getfenlei','index'];
    protected $noNeedRight = ['*'];






    public function list(){
       
        $post = $this->request->post();


        $map['start_time'] = ['<=',time()];
        $map['end_time'] = ['>=',time()];
        $map['shangjia_id'] = $post['mendian_id'];

        $list = Db::table('fa_pifa_activity')->where($map)->order('end_time asc,weigh desc')->select();

        $this->success('成功',$list);

    }   



    public function info(){
        $ActivityModel = new \app\admin\model\pifa\Activity;    
         $post = $this->request->post();

        try {
            $map['start_time'] = ['<=',time()];
            $map['end_time'] = ['>=',time()];
            $map['id'] = $post['id'];
            $activity = $ActivityModel->where($map)->find();
            $activity->goods_list = $activity->goods_list;
            $activity['time'] = $activity->end_time - time(); 
            $this->success('成功',$activity);
        } catch (Exception $e) {
              $this->error('失败');
        }
       
    }   
    
    public function index(){
        $ActivityModel = new \app\admin\model\pifa\Activity;    


        try {
             $map['start_time'] = ['<=',time()];
            $map['end_time'] = ['>=',time()];

            $activity = $ActivityModel->where($map)->limit(1)->order('end_time asc,weigh desc')->find();
            $activity->goods_list = $activity->goods_list;
            $activity['time'] = $activity->end_time - time(); 
            $this->success('成功',$activity);
        } catch (Exception $e) {
              $this->error('失败');
        }
       
    }   


    public function index2(){


        $post = $this->request->post();
        $ActivityModel = new \app\admin\model\pifa\Activity;    
        $map['id'] = $post['id'];
       
        $activity = $ActivityModel->where($map)->limit(1)->order('end_time asc')->find();
        $activity->goods_list = $activity->goods_list;
        $activity['time'] = $activity->end_time - time(); 
        $this->success('成功',$activity);
    }     


    public function pre()
    {
        $post = file_get_contents( "php://input");
        $post = json_decode($post,true);
        $ids = [];
        $num = 0;
        $price = 0;
        $price2 = 0;
        $is_youhui = 0;
        
        $result['yunfei'] = 0;

        $ActivityModel = new \app\admin\model\pifa\Activity;    
        $mapActivity['start_time'] = ['<=',time()];
        $mapActivity['end_time'] = ['>=',time()];
        $mapActivity['id'] = $post['activity_id'];
        $activity = $ActivityModel->where($mapActivity)->limit(1)->order('end_time asc')->find();

        if (empty($activity)) {
            $this->error('活动已结束');
        }

        foreach ($post['goods_list'] as $key => $value) {
            $map['fa_litestore_goods_spec.goods_id'] = $value['goods_id'];
            $map['fa_litestore_goods_spec.goods_spec_id'] = $value['sku_price_id'];
            $res = Goodsitem::with(['goods'])->where($map)->find();

            $mapkill['activity_id'] = $post['activity_id'];
            $mapkill['goods_id'] = $value['goods_id'];
            $mapkill['goods_sku_price_id'] = $value['sku_price_id'];
            $kill_info = Db::table('fa_pifa_activity_sku_price')->where($mapkill)->find();

            if (empty($kill_info)) {
                $this->error('商品已下架');
                break;
            }

            if ($kill_info['sales'] >= $kill_info['stock']) {
                 $this->error('库存不足');
                break;
            }
            $res['goods_price'] = $kill_info['price'];

            $res = $res->toArray();
            $post['goods_list'][$key]['info'] = $res;
            $num = $num + $value['goods_num'];
            $post['goods_list'][$key]['price'] = bcmul($res['goods_price'],$value['goods_num'],2);
            $post['goods_list'][$key]['price2'] = bcmul($res['goods_price2'],$value['goods_num'],2);
            $price = bcadd($price,$post['goods_list'][$key]['price'],2);
            $price2 = bcadd($price2,$post['goods_list'][$key]['price2'],2);
           
            $goods_total_weight = bcmul($res['goods_weight'], $value['goods_num'], 2);
            if (!empty($post['address_id'])) {
                $address = Db::table('fa_user_address')->find($post['address_id']);

                $Litestorefreight = Litestorefreight::with('rule')->find($res['goods']['delivery_id']);
                try {
                     $expressPrice = $Litestorefreight->calcTotalFee($value['goods_num'], $goods_total_weight, $address['city_id']);
                } catch (Exception $e) {
                    $this->error('不在配送区域');
                    break;
                }
                $expressPrice = $Litestorefreight->calcTotalFee($value['goods_num'], $goods_total_weight, $address['city_id']);
            }else{
                try {
                     $expressPrice = $Litestorefreight->calcTotalFee($value['goods_num'], $goods_total_weight, $address['city_id']);
                } catch (Exception $e) {
                    $this->error('不在配送区域');
                    break;
                } 
            }
            $result['yunfei'] = $result['yunfei']+$expressPrice;
        }   
  
        $zhekou = 0;
        $jisuan_youhui_price = $price;


       



        $result['new_goods_list'] = $post['goods_list'];
        $result['now_price'] = $jisuan_youhui_price+$result['yunfei'];
        $result['goods_num'] = $num;
        $result['goods_price'] = $price;
        $result['zhekou'] = $zhekou;


        $this->success("成功",$result);
    }




    public function createOrder()
    {
        $post = file_get_contents( "php://input");
        $post = json_decode($post,true);
        $ids = [];
        $num = [];
        $price = 0;
        $price2 = 0;


        if (empty($post['mendian_id'])) {
           $this->error('门店不存在');
        }
        $ActivityModel = new \app\admin\model\pifa\Activity;        
        $mapActivity['start_time'] = ['<=',time()];
        $mapActivity['end_time'] = ['>=',time()];
        $mapActivity['id'] = $post['activity_id'];
        $activity = $ActivityModel->where($mapActivity)->limit(1)->order('end_time asc')->find();

        if (empty($activity)) {
            $this->error('活动已结束');
        }

        $cat_id = [];
        $user = Db::table('fa_user')->find($this->auth->id);

        $youhui_id = $post['youhui_id'];

        
        $yunfei = 0;
        $feiyong = 0;
        $goods_price = 0;
        $goods_price3 = 0;
        $goods_price4 = 0;

        $spec_id = 0;
        $kill_info = [];
        $mapkill = [];
        foreach ($post['goods_list'] as $key => $value) {
          

            $map['fa_litestore_goods_spec.goods_id'] = $value['goods_id'];
            $map['fa_litestore_goods_spec.goods_spec_id'] = $value['sku_price_id'];

            array_push($cat_id,$value['sku_price_id']);
            $res = Goodsitem::with(['goods'])->where($map)->find();
            $res = $res->toArray();
            $post['goods_list'][$key]['info'] = $res;

            // if ($res['goods']['shangjia_id'] != $post['mendian_id']) {
            //     $this->error('数据异常');
            // }


            $mapkill['activity_id'] = $post['activity_id'];
            $mapkill['goods_id'] = $value['goods_id'];
            $mapkill['goods_sku_price_id'] = $value['sku_price_id'];
            $kill_info = Db::table('fa_pifa_activity_sku_price')->where($mapkill)->find();

            if (empty($kill_info)) {
                $this->error('商品已下架');
                break;
            }

            if ($kill_info['sales'] >= $kill_info['stock']) {
                $this->error('库存不足');
                break;
            }
            $res['goods_price'] = $kill_info['price'];


            $post['goods_list'][$key]['price'] = bcmul($res['goods_price'],$value['goods_num'],2);
            $post['goods_list'][$key]['price2'] = bcmul($res['goods_price2'],$value['goods_num'],2);

            

        
            $post['goods_list'][$key]['goods_price3'] = bcmul($res['goods_price3'],$value['goods_num'],2);
            $post['goods_list'][$key]['goods_price4'] = bcmul($res['goods_price4'],$value['goods_num'],2);

            $goods_price3 = bcadd($post['goods_list'][$key]['goods_price3'],$goods_price3,2);
            $goods_price4 = bcadd($post['goods_list'][$key]['goods_price4'],$goods_price4,2);
            


            $price = bcadd($price,$post['goods_list'][$key]['price'],2);
            $price2 = bcadd($price2,$post['goods_list'][$key]['price2'],2);

            $goods_total_weight = bcmul($res['goods_weight'], $value['goods_num'], 2);
            if (!empty($post['address_id'])) {
                $address = Db::table('fa_user_address')->find($post['address_id']);

                $Litestorefreight = Litestorefreight::with('rule')->find($res['goods']['delivery_id']);

                try {
                     $expressPrice = $Litestorefreight->calcTotalFee($value['goods_num'], $goods_total_weight, $address['city_id']);
                } catch (Exception $e) {
                    $this->error('不在配送区域');
                    break;
                }

                
            }else{


                try {
                    $expressPrice = $Litestorefreight->calcTotalFee($value['goods_num'], $goods_total_weight, 0);
                } catch (Exception $e) {
                    $this->error('不在配送区域');
                    break;
                }
            }

            $yunfei = $yunfei+$expressPrice;


        }   
        $new_goods_list = $post['goods_list'];


       
        $insdata['order_no'] = 'QF'.date('YmdHis') . $this->auth->id;
        $map3['user_id'] = $this->auth->id;
        $map3['id'] = $post['address_id'];
        $address = Db::table('fa_user_address')->where($map3)->find();
         if (empty($address)) {
           $this->error('地址不存在');
        }
     
        

        $store = Db::table('fa_pifa_shangjia')->field('*, ' . getDistanceBuilder($address['latitude'], $address['longitude']))->where('id','=',$post['mendian_id'])->find();


        if (!isset($store['distance']) || $store['distance'] > $store['service_radius']) {

       
            $this->error('当前收货地址不在配送范围');

        }


      

        $jisuan_youhui_price = $price;

        $youhui = [];
    
        Db::startTrans();
        try {

            $insdata['user_id'] = $this->auth->id;

            $user = Db::table('fa_user')->find($this->auth->id);

            if (!empty($user['inv_id'])) {
                $insdata['inv_id'] = $user['inv_id'];
            }
            
            $insdata['mendian_id'] = $post['mendian_id'];
            $insdata['activity_id'] = $post['activity_id'];
            $insdata['consignee'] = $address['consignee'];
            $insdata['phone'] = $address['phone'];
            $insdata['inv_id'] = $user['inv_id'];
            $insdata['address'] = $address['province_name'].$address['city_name'].$address['area_name'].$address['address'];
            $insdata['province_id'] = $address['province_id'];
            $insdata['city_id'] = $address['city_id'];
            $insdata['area_id'] = $address['area_id'];
            $insdata['lat'] = $address['latitude'];
            $insdata['lng'] = $address['longitude'];
            $insdata['goods_price'] = $jisuan_youhui_price;
            $insdata['goods_price3'] = $goods_price3;
            $insdata['shanghu_price'] = bcsub($insdata['goods_price'],$goods_price3,2);
            $insdata['price'] = $jisuan_youhui_price+$yunfei;
            $insdata['yunfei'] = $yunfei;
            $insdata['zhekou'] = 0;

            $insdata['emo'] = $post['remark'];
            $insdata['peisong_time'] = $post['peisong_time'];
            $insdata['mendian_id'] = $post['mendian_id'];
            $insdata['createtime'] = time();
            $insdata['createday'] = date('Y-m-d');
            $insdata['createmonth'] = date('Y-m');
            $insdata['updatetime'] = time();
            $insdata['orderstate'] = '0';
            $insdata['expiretime'] = time()+60*30;

            if (!empty($youhui)) {
                $insdata['youhui'] = $youhui['youhuijuan']['price'];
                $insdata['price'] = $insdata['price'] - $youhui['youhuijuan']['price'];
            }


            $res = Db::table('fa_pifa_order')->insertGetId($insdata);

            foreach ($new_goods_list as $key => $value) {

              
                $ins = [];
                $ins['order_id'] = $res;
                $ins['user_id'] = $this->auth->id;
                $ins['goods_id'] = $value['goods_id'];
                $ins['shangjia_id'] = $post['mendian_id'];
                $ins['gongyingshang_id'] = $value['info']['goods']['gongyingshang_id'];
                $ins['goods_name'] = $value['info']['goods']['goods_name'];
                $ins['image'] = $value['info']['goods']['image'];
                $ins['goods_item_id'] = $value['info']['goods_spec_id'];
                $ins['name'] = $value['info']['miaoshu'];
                $ins['goods_no'] = $value['info']['goods_no'];
                $ins['goods_num'] = $value['goods_num'];
                $ins['goods_price3'] = $value['goods_price3'];
                 Db::table('fa_pifa_activity_sku_price')->where($mapkill)->setInc('sales',$value['goods_num']);
                $ins['goods_price4'] = $value['goods_price4'];
                $ins['price'] = $value['price'];
                if (!empty($user_vip)) {
                      $ins['price'] = $value['price2'];
                }
                $ins['shanghu_price'] = bcsub($ins['price'],$value['goods_price3'],2);
                Db::table('fa_pifa_orderitem')->insert($ins);
            }

         


   

            Db::commit();
            $this->success("成功",$res);
        } catch (Exception $e) {
             Db::rollback();
            //出错回滚
             $this->error($e->getMessage());
            Log::error($e);
            $this->error(__('下单失败'));

        }

        
    }

}